package com.kyrie.lib_sys.interceptor;


import cn.dev33.satoken.stp.StpUtil;
import com.kyrie.lib_sys.context.RequestHolder;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * 自定义拦截器,拦截请求获取用户信息和请求路径
 *
 * @author heefM
 * @date 2025-09-02
 */
@Component
public class LogInterceptor implements HandlerInterceptor {

    /**
     * 从拦截器中获取请求和用户信息
     *
     * @param request
     * @param response
     * @param handler
     * @return
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        try {
            // 从Sa-Token中获取当前登录用户---拦截获取用户信息,set到上下文
            if (StpUtil.isLogin()) {
                String username = StpUtil.getLoginIdAsString();
                RequestHolder.setCurrentUser(username);
            } else {
                // 如果未登录，设置为匿名用户
                RequestHolder.setCurrentUser("anonymous");
            }
        } catch (Exception e) {
            // 如果获取用户信息失败，设置为匿名用户
            RequestHolder.setCurrentUser("anonymous");
        }
        return true;
    }

    /**
     * 清除应用上下文
     *
     * @param request
     * @param response
     * @param handler
     * @param ex
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        // 清除ThreadLocal中的用户信息，防止内存泄漏
        RequestHolder.clear();
    }
}
